//
//  HomeViewController.m
//  FNMenu
//
//  Created by 航汇聚科技 on 2018/9/5.
//  Copyright © 2018年 Yi Zhou. All rights reserved.
//

#import "HomeViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import <Masonry/Masonry.h>
#import <SDWebImage/UIButton+WebCache.h>
#import <LYEmptyView/UIView+Empty.h>
#import "UIViewController+Empty.h"
#import "NSDictionary+Safety.h"
#import "NSArray+Safety.h"
#import "LLFullScreenAdView.h"
#import "WaterFallCollectionCell.h"
#import "WaterFallHeaderReusableView.h"
#import "KindViewController.h"
#import "DetailViewController.h"
#import "ListViewController.h"
#import "SearchViewController.h"
#import "ShareViewController.h"
#import "PlayingLineView.h"
#import "PlayerManager.h"
#import "NetManager.h"
#import "User.h"
@interface HomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate, WaterFallHeaderCycleViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *searchItem;
@property (weak, nonatomic) IBOutlet UIButton *musicButtonItem;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) UIView *shareContentView;
@property (nonatomic, strong) UIButton *shareButton;
@property (nonatomic, strong) LLFullScreenAdView *adView;
@property (nonatomic, strong) PlayingLineView *line;
@property (nonatomic, strong) NSArray *homeArray;
@property (nonatomic, strong) NSArray *foodKindArray;
@property (nonatomic, copy) NSString *buttonRelatedAddress;
@property (nonatomic, copy) NSString *recommandCookName;
@property (nonatomic, strong) NSDictionary *shareInfo;
@end
@implementation HomeViewController(MusicPlayState)

- (void)addThread {
    [self performSelector:@selector(changeRightItemIcon) withObject:nil];
}

- (void)changeRightItemIcon {
    UIButton *button = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
    UIView *superView = button.superview;
    if ([PlayerManager defaultPlayer].isPlaying) {
        if (![superView.subviews containsObject:self.line]) {
            [button setImage:nil forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
            [superView addSubview:self.line];
            [superView bringSubviewToFront:button];
        }
    }else {
        [button setImage:[UIImage imageNamed:@"playStartIconImage"] forState:UIControlStateNormal];
        if ([superView.subviews containsObject:self.line]) {
            [self.line removeFromSuperview];
        }
    }
}

@end
@implementation HomeViewController
#define keyWindow [UIApplication sharedApplication].keyWindow
#pragma mark - lifeCycle
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.shareContentView];
    [_shareContentView addSubview:self.shareButton];
    [keyWindow addSubview:self.adView];
    [keyWindow bringSubviewToFront:_adView];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self fetchOtherData];
        [self fetchData];
    }];
    //设置空内容占位图
    self.collectionView.ly_emptyView = [self emptyViewLoadDataBlock:^{
        [self registerTourMode];
        [self fetchData];
    }];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self addThread];
    [self fetchOtherData];
    [self fetchData];
    [self registerTourMode];
    CGFloat bottom = self.tabBarController.tabBar.bounds.size.height/2 + 30;
    __weak typeof(self.view) weakView = self.view;
    [_shareContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakView.mas_right).offset(-10);
        make.bottom.equalTo(weakView.mas_bottom).offset(-bottom);
        make.size.mas_equalTo(CGSizeMake(shareContentViewWidth, shareContentViewWidth));
    }];
    __weak typeof(_shareContentView) weakShareContentView = _shareContentView;
    [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakShareContentView);
    }];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    __weak typeof(self) ws = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([keyWindow.subviews containsObject:ws.adView]) {
            [ws.adView removeFromSuperview];
        }
    });
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    SearchViewController *searchVC = [SearchViewController searchVCFromStoryBoard];
    searchVC.searchKeywords = textField.text;
    [self.navigationController pushViewController:searchVC animated:YES];
    return [textField resignFirstResponder];
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.homeArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WaterFallCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"waterFallCell" forIndexPath:indexPath];
    cell.foodInfo = [self.homeArray safeObjectAtIndex:indexPath.item];
    return cell;
}
static BOOL firstUpdate = YES;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        WaterFallHeaderReusableView *headerView = (WaterFallHeaderReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"waterFallHeader" forIndexPath:indexPath];
        [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/classify" params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            self.foodKindArray = [responseObject safeObjectForKey:@"result"];
            headerView.foodKinds = @[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"][0],
                                     [[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"][1],
                                     [[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"][2],
                                     @{@"name":@"更多"}];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        headerView.delegate = self;
        if (self.homeArray.count == 0) {
            headerView.hidden = YES;
        }else {
            headerView.hidden = NO;
        }
        if (firstUpdate) {
            firstUpdate = NO;
        }
        return headerView;
    }
    return nil;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detailVC = [DetailViewController detailVCFromStroyBoard];
    detailVC.title = [[self.homeArray safeObjectAtIndex:indexPath.item] safeObjectForKey:@"title"];
    detailVC.view.backgroundColor = [UIColor whiteColor];
    NSInteger foodID = [[[self.homeArray safeObjectAtIndex:indexPath.item] safeObjectForKey:@"id"] integerValue];
    detailVC.foodID = foodID;
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/details" params:@{@"id":[NSString stringWithFormat:@"%ld",(long)foodID], @"uid":[User userID]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *foodInfo = [[[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"] safeObjectAtIndex:0];
        detailVC.foodInfo = foodInfo;
        [self.navigationController pushViewController:detailVC animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - WaterFallHeaderCycleViewDelegate
- (void)didSelectItemAtIndex:(NSInteger)index {
    ListViewController *listVC = [ListViewController listVCFromStroyBoard];
    listVC.cID = [[[[[self.foodKindArray safeObjectAtIndex:1] safeObjectForKey:@"list"] safeObjectAtIndex:index] safeObjectForKey:@"id"] integerValue];
    listVC.title = [[[[self.foodKindArray safeObjectAtIndex:1]  safeObjectForKey:@"list"] safeObjectAtIndex:index] safeObjectForKey:@"name"];
    [self.navigationController pushViewController:listVC animated:YES];
}
- (void)locationName:(NSString *)locationName {
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    if ([predicate evaluateWithObject:locationName]) {
        self.recommandCookName = locationName;
    }
    [self fetchData];
}
#pragma mark - event response
- (void)toShareAction:(UIButton *)sender {
    if ([[self.shareInfo safeObjectForKey:@"address"] length] != 0) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[self.shareInfo safeObjectForKey:@"address"]]];
        return;
    }
    ShareViewController *shareVC = [ShareViewController shareVCFromStoryBoard];
    shareVC.info = self.shareInfo;
    [self presentViewController:shareVC animated:YES completion:nil];
}
- (IBAction)tapMoreImgGesture:(UITapGestureRecognizer *)sender {
    switch (sender.view.tag) {
        case 1004:
            [self pushToKindVC];
            break;
        case 1003:
            [self pushToListVC:[[[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"] safeObjectAtIndex:2] safeObjectForKey:@"id"] integerValue] title:[[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"] safeObjectAtIndex:2] safeObjectForKey:@"name"]];
            break;
        case 1002:
            [self pushToListVC:[[[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"] safeObjectAtIndex:1] safeObjectForKey:@"id"] integerValue] title:[[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"] safeObjectAtIndex:1] safeObjectForKey:@"name"]];
            break;
        case 1001:
            [self pushToListVC:[[[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"] safeObjectAtIndex:0] safeObjectForKey:@"id"] integerValue] title:[[[[self.foodKindArray safeObjectAtIndex:0] safeObjectForKey:@"list"] safeObjectAtIndex:0] safeObjectForKey:@"name"]];
            break;
        default:
            break;
    }
}
- (void)pushToKindVC {
    [self.navigationController pushViewController:[KindViewController kindViewControllerFromStoryboard] animated:YES];
}
- (void)pushToListVC:(NSInteger)cid title:(NSString *)title {
    ListViewController *listVC = [ListViewController listVCFromStroyBoard];
    listVC.cID = cid;
    listVC.title = title;
    [self.navigationController pushViewController:listVC animated:YES];
}
#pragma mark - private
- (void)fetchData {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/menu/recipes" params:@{@"uid":[User userID], @"menu":self.recommandCookName==nil?@"健康":self.recommandCookName} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.homeArray = [[responseObject safeObjectForKey:@"result"] safeObjectForKey:@"data"];
        if (self.homeArray.count == 0) {
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.collectionView.mj_header endRefreshing];
    }];
}
- (void)fetchOtherData {
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/search" params:@{@"uid":[User userID]} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.searchItem.placeholder = [NSString stringWithFormat:@"她们正在搜 %@",[[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"default"]];
        if ( self.recommandCookName.length == 0) {
            self.recommandCookName = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"recommendMenu"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    
    LLFullScreenAdView *adView = (LLFullScreenAdView *)[keyWindow viewWithTag:100];
    [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/gonggao" params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *icon = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"icon"];
        self.buttonRelatedAddress = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"address"];
        self.shareInfo = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"share"];
#if DEBUG
        [self.shareButton sd_setImageWithURL:[NSURL URLWithString:[icon stringByReplacingOccurrencesOfString:@"https" withString:@"http"]] forState:UIControlStateNormal];
#else
        [self.shareButton sd_setImageWithURL:[NSURL URLWithString:icon] forState:UIControlStateNormal];
#endif
        NSString *adStr = [[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"adIcon"];
        if (adStr.length != 0) {
            [adView reloadAdImageWithUrl:adStr];
        }else {
            [adView removeFromSuperview];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [adView removeFromSuperview];
    }];
}
- (void)registerTourMode {
    if (![User isLogin]) {
        [[NetManager defaultNetManager] fetchNetDataWithURLStr:@"home/users/register" params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@",responseObject);
            [User saveUserId:[[responseObject safeObjectForKey:@"show_data"] safeObjectForKey:@"id"]];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];
    }
}
#pragma mark - getter
- (UIButton *)shareButton {
    if (!_shareButton) {
        _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shareButton addTarget:self action:@selector(toShareAction:) forControlEvents:UIControlEventTouchUpInside];
        _shareButton.layer.shadowOffset = CGSizeMake(3, 3);
        _shareButton.layer.shadowRadius = 3;
        _shareButton.layer.shadowOpacity = 0.7;
        _shareButton.layer.shadowColor = [UIColor blackColor].CGColor;
        //创建动画
        CAKeyframeAnimation *keyAnimaion = [CAKeyframeAnimation animation];
        keyAnimaion.keyPath = @"transform.rotation";
        keyAnimaion.values = @[@(-10 / 180.0 * M_PI),@(10 /180.0 * M_PI),@(-10/ 180.0 * M_PI)];
        keyAnimaion.removedOnCompletion = NO;
        keyAnimaion.fillMode = kCAFillModeForwards;
        keyAnimaion.duration = 0.3;
        keyAnimaion.repeatCount = MAXFLOAT;
        [_shareButton.layer addAnimation:keyAnimaion forKey:nil];
    }
    return _shareButton;
}
static CGFloat shareContentViewWidth = 100;
- (UIView *)shareContentView {
    if (!_shareContentView) {
        _shareContentView = [UIView new];
        _shareContentView.layer.masksToBounds = YES;
        _shareContentView.layer.cornerRadius = shareContentViewWidth/2;
    }
    return _shareContentView;
}
- (LLFullScreenAdView *)adView {
    if (!_adView) {
        _adView = [[LLFullScreenAdView alloc] init];
        _adView.tag = 100;
        _adView.duration = 5;
        _adView.waitTime = 0;
        _adView.skipType = SkipButtonTypeCircleAnimationTest;
        _adView.adImageTapBlock = ^(NSString *content) {
        };
        _adView.backgroundColor = [UIColor clearColor];
    }
    return _adView;
}
- (PlayingLineView *)line {
    if (!_line) {
        UIButton *button = (UIButton *)self.navigationItem.rightBarButtonItem.customView;
            _line = [[PlayingLineView alloc] initWithFrame:button.bounds lineWidth:1 lineColor:[UIColor redColor]];
    }
    return _line;
}
@end
